package clientereligadora.formularios;

import clientereligadora.conexao.Conexao;
import clientereligadora.operacoes.Operacao;
import com.mysql.jdbc.Blob;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.*;
import java.sql.SQLException;
import java.text.Normalizer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 *
 * @author Leandro Aquino
 */
final class FormCadastroUsuario extends javax.swing.JFrame {
    Operacao operacao = new Operacao();

     
    FormLogin tela_login = new FormLogin();
    String nome;
    String login;
    String senha;
    String contraSenha;
    Date dataUltimAcesso;
    byte [] foto;
    FileInputStream fis;
    SimpleDateFormat dateFormatDB = new SimpleDateFormat("yyyy-MM-dd");
    Conexao conn;
    

    /**
     * Creates new form frm_Principal
     */
    public FormCadastroUsuario(Conexao conn) {
        this.conn = conn;
        initComponents();

        carregaChebox();
   
        //LIMITA CARACTERES AO DIGITAR,NUMEROS E OUTRAS SENTENÇAS
        txt_nomeUsuario.setDocument(new formatNome());
        txt_login.setDocument(new tirarAcento());
        jPasswordField_senha.setDocument(new verificaSenha());
        jPasswordField_ConfirmaSenha.setDocument(new verificaSenha());

        //arrastando o texto com tecla Ctrl pressionada
        txt_nomeUsuario.setDragEnabled(true);
        txt_login.setDragEnabled(true);

        setLocationRelativeTo(null); // CENTRALIZA PAGINA

        resetUsuarios();

            // LAYOUT DE JOPTIONPANES
        Icon warning = new ImageIcon("C:\\cfgReligadora\\icons\\Warning.png");
        Icon ok = new ImageIcon("C:\\cfgReligadora\\icons\\OK.png");
        Icon erro = new ImageIcon("C:\\cfgReligadora\\icons\\Error.png");
        Icon info = new ImageIcon("C:\\cfgReligadora\\icons\\Infor.png");
        Icon questionIcon = new ImageIcon("C:\\cfgReligadora\\icons\\question.png");


        UIManager.put("OptionPane.yesButtonText", "Sim");
        UIManager.put("OptionPane.noButtonText", "Não");
        UIManager.put("OptionPane.cancelButtonText", "Cancelar");
        UIManager.put("OptionPane.informationIcon", info);
        UIManager.put("OptionPane.errorIcon", erro);
        UIManager.put("OptionPane.questionIcon", questionIcon);
        UIManager.put("OptionPane.warningIcon", warning);


        //LAYOUT CAIXA DE SELEÇÃO
        UIManager.put("FileChooser.openDialogTitleText", "Abrir");
        UIManager.put("FileChooser.lookInLabelText", "Procurar em");
        UIManager.put("FileChooser.saveInLabelText", "Salvar em");
        UIManager.put("FileChooser.openButtonText", "Abrir");
        UIManager.put("FileChooser.saveButtonText", "Salvar");
        UIManager.put("FileChooser.cancelButtonText", "Cancelar");
        UIManager.put("FileChooser.fileNameLabelText", "Nome do Arquivo");
        UIManager.put("FileChooser.filesOfTypeLabelText", "Tipo de Arquivo");
        UIManager.put("FileChooser.openButtonToolTipText", "Abrir o Arquivo Selecionado");
        UIManager.put("FileChooser.saveButtonToolTipText", "Salvar Arquivo Selecionado");
        UIManager.put("FileChooser.cancelButtonToolTipText", "Cancelar");
        UIManager.put("FileChooser.fileNameHeaderText", "Nome");
        UIManager.put("FileChooser.upFolderToolTipText", "Subir um Nível");
        UIManager.put("FileChooser.homeFolderToolTipText", "Área de Trabalho");
        UIManager.put("FileChooser.newFolderToolTipText", "Criar Nova Pasta");
        UIManager.put("FileChooser.listViewButtonToolTipText", "Lista");
        UIManager.put("FileChooser.newFolderButtonText", "Criar Nova Pasta");
        UIManager.put("FileChooser.renameFileButtonText", "Renomear");
        UIManager.put("FileChooser.deleteFileButtonText", "Deletar");
        UIManager.put("FileChooser.filterLabelText", "Tipo");
        UIManager.put("FileChooser.detailsViewButtonToolTipText", "Detalhes");
        UIManager.put("FileChooser.fileSizeHeaderText", "Tamanho");
        UIManager.put("FileChooser.fileDateHeaderText", "Data de Modificação");
        UIManager.put("FileChooser.acceptAllFileFilterText", "Todos os Arquivos");




    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPasswordField_senha = new javax.swing.JPasswordField();
        btn_cadastrar = new javax.swing.JButton();
        jPasswordField_ConfirmaSenha = new javax.swing.JPasswordField();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        txt_nomeUsuario = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        cbx_tipoUser = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        btn_cancelar = new javax.swing.JButton();
        imgUser = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        txt_login = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jcbx_todos = new javax.swing.JCheckBox();
        jcbx_incluir = new javax.swing.JCheckBox();
        jcbx_consultar = new javax.swing.JCheckBox();
        jcbx_alterar = new javax.swing.JCheckBox();
        jcbx_excluir = new javax.swing.JCheckBox();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("CADASTRO DE USUARIOS");
        setResizable(false);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setAutoscrolls(true);

        jPasswordField_senha.setForeground(new java.awt.Color(0, 0, 50));
        jPasswordField_senha.setToolTipText("Senha");
        jPasswordField_senha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPasswordField_senhaActionPerformed(evt);
            }
        });
        jPasswordField_senha.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jPasswordField_senhaKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jPasswordField_senhaKeyTyped(evt);
            }
        });

        btn_cadastrar.setBackground(new java.awt.Color(255, 255, 255));
        btn_cadastrar.setFont(new java.awt.Font("Arial", 0, 10)); // NOI18N
        btn_cadastrar.setForeground(new java.awt.Color(0, 0, 50));
        btn_cadastrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/36.png"))); // NOI18N
        btn_cadastrar.setMnemonic('C');
        btn_cadastrar.setText("Cadastrar");
        btn_cadastrar.setToolTipText("Cadastrar Usuario");
        btn_cadastrar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btn_cadastrar.setIconTextGap(5);
        btn_cadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_cadastrarActionPerformed(evt);
            }
        });

        jPasswordField_ConfirmaSenha.setForeground(new java.awt.Color(0, 0, 50));
        jPasswordField_ConfirmaSenha.setToolTipText("Confirmar Senha");
        jPasswordField_ConfirmaSenha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPasswordField_ConfirmaSenhaActionPerformed(evt);
            }
        });
        jPasswordField_ConfirmaSenha.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jPasswordField_ConfirmaSenhaKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jPasswordField_ConfirmaSenhaKeyTyped(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Arial", 0, 10)); // NOI18N
        jLabel6.setForeground(new java.awt.Color(0, 0, 50));
        jLabel6.setText("Nome:");

        jLabel7.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
        jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel7.setText("Cadastro de Usuários");
        jLabel7.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

        txt_nomeUsuario.setForeground(new java.awt.Color(0, 0, 50));
        txt_nomeUsuario.setToolTipText("Nome do Usuário");
        txt_nomeUsuario.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                txt_nomeUsuarioCaretUpdate(evt);
            }
        });
        txt_nomeUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txt_nomeUsuarioActionPerformed(evt);
            }
        });
        txt_nomeUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txt_nomeUsuarioKeyPressed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Arial", 0, 10)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(0, 0, 50));
        jLabel1.setText("Login:");

        jLabel10.setFont(new java.awt.Font("Arial", 0, 10)); // NOI18N
        jLabel10.setForeground(new java.awt.Color(0, 0, 50));
        jLabel10.setText("Confirmar Senha:");

        cbx_tipoUser.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        cbx_tipoUser.setForeground(new java.awt.Color(0, 0, 50));
        cbx_tipoUser.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "-", "Administrador", "Usuarios" }));
        cbx_tipoUser.setToolTipText("Perfil do Usuário");
        cbx_tipoUser.addMouseWheelListener(new java.awt.event.MouseWheelListener() {
            public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
                cbx_tipoUserMouseWheelMoved(evt);
            }
        });
        cbx_tipoUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbx_tipoUserActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Arial", 0, 10)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(0, 0, 50));
        jLabel3.setText("Permissão:");

        jLabel2.setFont(new java.awt.Font("Arial", 0, 10)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(0, 0, 50));
        jLabel2.setText("Senha:");

        btn_cancelar.setBackground(new java.awt.Color(255, 255, 255));
        btn_cancelar.setFont(new java.awt.Font("Arial", 0, 10)); // NOI18N
        btn_cancelar.setForeground(new java.awt.Color(0, 0, 50));
        btn_cancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/52.png"))); // NOI18N
        btn_cancelar.setMnemonic('n');
        btn_cancelar.setText("Cancelar");
        btn_cancelar.setToolTipText("Cadastrar Usuario");
        btn_cancelar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btn_cancelar.setIconTextGap(5);
        btn_cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_cancelarActionPerformed(evt);
            }
        });

        imgUser.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        imgUser.setForeground(new java.awt.Color(0, 0, 50));
        imgUser.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        imgUser.setToolTipText("Adicionar uma imagem");
        imgUser.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        imgUser.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        imgUser.setFocusable(false);
        imgUser.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        imgUser.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                imgUserMouseClicked(evt);
            }
        });

        jButton1.setBackground(new java.awt.Color(255, 255, 255));
        jButton1.setFont(new java.awt.Font("Arial", 0, 10)); // NOI18N
        jButton1.setForeground(new java.awt.Color(0, 0, 50));
        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/3.png"))); // NOI18N
        jButton1.setText("Foto");
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        jButton1.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setBackground(new java.awt.Color(255, 255, 255));
        jButton2.setFont(new java.awt.Font("Arial", 0, 10)); // NOI18N
        jButton2.setForeground(new java.awt.Color(0, 0, 50));
        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/39.png"))); // NOI18N
        jButton2.setMnemonic('A');
        jButton2.setText("Alterar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        txt_login.setForeground(new java.awt.Color(0, 0, 50));
        txt_login.setToolTipText("Nome do Usuário");
        txt_login.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txt_loginKeyPressed(evt);
            }
        });

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Permissões", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 0, 10), java.awt.Color.blue)); // NOI18N
        jPanel2.setForeground(new java.awt.Color(0, 0, 50));

        jcbx_todos.setBackground(new java.awt.Color(255, 255, 255));
        jcbx_todos.setFont(new java.awt.Font("Arial", 0, 9)); // NOI18N
        jcbx_todos.setForeground(new java.awt.Color(0, 0, 50));
        jcbx_todos.setText("Todos");

        jcbx_incluir.setBackground(new java.awt.Color(255, 255, 255));
        jcbx_incluir.setFont(new java.awt.Font("Arial", 0, 9)); // NOI18N
        jcbx_incluir.setForeground(new java.awt.Color(0, 0, 50));
        jcbx_incluir.setText("Incluir");
        jcbx_incluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcbx_incluirActionPerformed(evt);
            }
        });

        jcbx_consultar.setBackground(new java.awt.Color(255, 255, 255));
        jcbx_consultar.setFont(new java.awt.Font("Arial", 0, 9)); // NOI18N
        jcbx_consultar.setForeground(new java.awt.Color(0, 0, 50));
        jcbx_consultar.setText("Consultar");

        jcbx_alterar.setBackground(new java.awt.Color(255, 255, 255));
        jcbx_alterar.setFont(new java.awt.Font("Arial", 0, 9)); // NOI18N
        jcbx_alterar.setForeground(new java.awt.Color(0, 0, 50));
        jcbx_alterar.setText("Alterar");

        jcbx_excluir.setBackground(new java.awt.Color(255, 255, 255));
        jcbx_excluir.setFont(new java.awt.Font("Arial", 0, 9)); // NOI18N
        jcbx_excluir.setForeground(new java.awt.Color(0, 0, 50));
        jcbx_excluir.setText("Excluir");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jcbx_incluir)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jcbx_alterar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jcbx_excluir)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jcbx_consultar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jcbx_todos)
                .addContainerGap(28, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jcbx_incluir)
                    .addComponent(jcbx_alterar)
                    .addComponent(jcbx_excluir)
                    .addComponent(jcbx_consultar)
                    .addComponent(jcbx_todos))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(147, 147, 147)
                        .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addGap(200, 200, 200)
                                .addComponent(jLabel1))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(txt_nomeUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(6, 6, 6)
                                        .addComponent(txt_login, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGap(1, 1, 1)
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(jPanel1Layout.createSequentialGroup()
                                                .addComponent(jLabel2)
                                                .addGap(53, 53, 53)
                                                .addComponent(jLabel10)
                                                .addGap(39, 39, 39)
                                                .addComponent(jLabel3))
                                            .addGroup(jPanel1Layout.createSequentialGroup()
                                                .addComponent(jPasswordField_senha, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(10, 10, 10)
                                                .addComponent(jPasswordField_ConfirmaSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(6, 6, 6)
                                                .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(7, 7, 7)
                                                .addComponent(cbx_tipoUser, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))))
                                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(18, 18, 18)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(imgUser, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(26, 26, 26)
                                .addComponent(btn_cadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(33, 33, 33)
                                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(30, 30, 30)
                                .addComponent(btn_cancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4)))
                .addGap(0, 20, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jLabel1))
                .addGap(6, 6, 6)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txt_nomeUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txt_login, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel10)
                            .addComponent(jLabel3))
                        .addGap(6, 6, 6)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPasswordField_senha, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jPasswordField_ConfirmaSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(1, 1, 1)
                                .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(cbx_tipoUser, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(5, 5, 5)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(imgUser, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(6, 6, 6)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(43, 43, 43)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(1, 1, 1)
                        .addComponent(btn_cadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btn_cancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addGap(283, 283, 283))
        );

        getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 490, 300));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btn_cadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_cadastrarActionPerformed


        dataUltimAcesso = new Date();

        String dat = dateFormatDB.format(dataUltimAcesso);

        nome = txt_nomeUsuario.getText().toString().toUpperCase();

        login = txt_login.getText().toString();

        senha = jPasswordField_senha.getText();

        contraSenha = jPasswordField_ConfirmaSenha.getText();

        if (nome.equals("") || nome == null) {
            JOptionPane.showMessageDialog(null, "CAMPO NOME EM BRANCO");
        } else if (login.equals("") || login == null) {
            JOptionPane.showMessageDialog(null, "CAMPO LOGIN EM BRANCO");
        } else if (senha.equals("") || senha == null) {
            JOptionPane.showMessageDialog(null, "CAMPO SENHA EM BRANCO");
        } else if (contraSenha.equals("") || contraSenha == null) {
            JOptionPane.showMessageDialog(null, "CAMPO CONFIRMAR SENHA EM BRANCO");
        } else {
            
                try {
                    //  inserir.inserirUsuario(nome, login, senha, "ATVO", dataUltimAcesso, foto);
                          //insereImagem(login, foto, fis);
                      inserirBlob(foto);
                } catch (SQLException ex) {
                    Logger.getLogger(FormCadastroUsuario.class.getName()).log(Level.SEVERE, null, ex);
                }
            
            resetUsuarios();
        }


    }//GEN-LAST:event_btn_cadastrarActionPerformed

    private void cbx_tipoUserMouseWheelMoved(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_cbx_tipoUserMouseWheelMoved
        // TODO add your handling code here:

        int count = cbx_tipoUser.getItemCount();

        if (count < 2) {
            return;
        }

        int index = cbx_tipoUser.getSelectedIndex();
        if (index == -1) {
            index = 0;
        }

        // VOLTA O ITEM ANTERIOR
        if (evt.getWheelRotation() < 0) {
            if (index > 0) {
                cbx_tipoUser.setSelectedIndex(index - 1);
            }
        } // PULA O PROXIMO ITEM
        else {
            if (index < count - 1) {
                cbx_tipoUser.setSelectedIndex(index + 1);
            }
        }
        evt.consume();
}//GEN-LAST:event_cbx_tipoUserMouseWheelMoved

    private void btn_cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_cancelarActionPerformed
        try {
            capturaImagem(10);
        } catch (IOException ex) {
            Logger.getLogger(FormCadastroUsuario.class.getName()).log(Level.SEVERE, null, ex);
        }
   
    }//GEN-LAST:event_btn_cancelarActionPerformed

    private void imgUserMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_imgUserMouseClicked
        try {
            try {
                carregaImagemUser();
            } catch (SQLException ex) {
                Logger.getLogger(FormCadastroUsuario.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (IOException ex) {
            Logger.getLogger(FormCadastroUsuario.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_imgUserMouseClicked

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            try {
                carregaImagemUser();
            } catch (SQLException ex) {
                Logger.getLogger(FormCadastroUsuario.class.getName()).log(Level.SEVERE, null, ex);
            }

        } catch (IOException ex) {
            Logger.getLogger(FormCadastroUsuario.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton1ActionPerformed
      public void liberaChebox() {


          for (Component cp : jPanel2.getComponents()) {
              cp.setEnabled(true);

          }
          jcbx_alterar.setSelected(false);
          jcbx_excluir.setSelected(false);
          jcbx_consultar.setSelected(false);
          jcbx_incluir.setSelected(false);
          jcbx_todos.setSelected(false);

      }

      public void carregaChebox() {


          for (Component cp : jPanel2.getComponents()) {
              cp.setEnabled(false);

          }
          jcbx_alterar.setSelected(false);
          jcbx_excluir.setSelected(false);
          jcbx_consultar.setSelected(false);
          jcbx_incluir.setSelected(false);
          jcbx_todos.setSelected(false);


      }

      public void bloqueiaChecbox() {
          for (Component cp : jPanel2.getComponents()) {
              cp.setEnabled(false);

          }

          jcbx_alterar.setSelected(true);
          jcbx_excluir.setSelected(true);
          jcbx_consultar.setSelected(true);
          jcbx_incluir.setSelected(true);
          jcbx_todos.setSelected(true);


      }
    private void cbx_tipoUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbx_tipoUserActionPerformed

        String permissao = cbx_tipoUser.getSelectedItem().toString();

        if (permissao.equals("Administrador")) {
            bloqueiaChecbox();

        } else if (permissao.equals("Usuarios")) {

            liberaChebox();
        } else {
            JOptionPane.showMessageDialog(this, "PERFIL SELECIONADO INCORRETO \n"
                    + "VERIFIQUE OS CAMPOS SELECIONADOS ! ");
        }

    }//GEN-LAST:event_cbx_tipoUserActionPerformed

    private void jPasswordField_senhaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField_senhaKeyTyped
        // TODO add your handling code here:
    }//GEN-LAST:event_jPasswordField_senhaKeyTyped

    private void jPasswordField_ConfirmaSenhaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField_ConfirmaSenhaKeyTyped
        // TODO add your handling code here:
    }//GEN-LAST:event_jPasswordField_ConfirmaSenhaKeyTyped

    private void jPasswordField_senhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPasswordField_senhaActionPerformed
    }//GEN-LAST:event_jPasswordField_senhaActionPerformed

    private void jPasswordField_ConfirmaSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPasswordField_ConfirmaSenhaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jPasswordField_ConfirmaSenhaActionPerformed

    private void txt_nomeUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_nomeUsuarioActionPerformed
    }//GEN-LAST:event_txt_nomeUsuarioActionPerformed

    private void txt_nomeUsuarioKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_nomeUsuarioKeyPressed
        int key = evt.getKeyCode();
        if (key == KeyEvent.VK_ENTER) {

            if ((txt_nomeUsuario.getText().equals(""))) {

                JOptionPane.showMessageDialog(this, "PREENCHA OS CAMPOS CORRETAMENTE\nCAMPO 'NOME DO USUARIO' EM BRANCO \n",
                        "ATENÇÃO", JOptionPane.WARNING_MESSAGE);

                txt_nomeUsuario.setText("");
                txt_nomeUsuario.requestFocus();

            } else {

                ((JTextField) (evt.getSource())).transferFocus();
            }
        }
    }//GEN-LAST:event_txt_nomeUsuarioKeyPressed

    private void jPasswordField_senhaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField_senhaKeyPressed
        verificaCapsLock();
        int key = evt.getKeyCode();
        if (key == KeyEvent.VK_ENTER) {

            if ((jPasswordField_senha.getText().equals(""))) {

                JOptionPane.showMessageDialog(this, "PREENCHA OS CAMPOS CORRETAMENTE", "ATENÇÃO", JOptionPane.WARNING_MESSAGE);
                JOptionPane.showMessageDialog(this, "CAMPO 'SENHA' EM BRANCO! \n"
                        + "VERIFIQUE OS CAMPOS DIGITADOS ");

                jPasswordField_senha.requestFocus();

            } else {
                ((JTextField) (evt.getSource())).transferFocus();
            }
        }
    }//GEN-LAST:event_jPasswordField_senhaKeyPressed

    private void jPasswordField_ConfirmaSenhaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField_ConfirmaSenhaKeyPressed

        verificaCapsLock();
        int key = evt.getKeyCode();

        //((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Tab))
        //if ((key == KeyEvent.VK_ENTER) &&(key == KeyEvent.VK_TAB) ){
        if (key == KeyEvent.VK_ENTER) {
            if ((jPasswordField_ConfirmaSenha.getText().equals(""))) {

                JOptionPane.showMessageDialog(this, "PREENCHA OS CAMPOS CORRETAMENTE", "ATENÇÃO", JOptionPane.WARNING_MESSAGE);
                JOptionPane.showMessageDialog(this, "CAMPO 'CONFIRMA SENHA' EM BRANCO! \n"
                        + "VERIFIQUE OS CAMPOS DIGITADOS ");
                jPasswordField_ConfirmaSenha.requestFocus();
            }
            if ((jPasswordField_senha.getText() == null ? (jPasswordField_ConfirmaSenha.getText()) == null : jPasswordField_senha.getText().equals(jPasswordField_ConfirmaSenha.getText()))) {

                ((JTextField) (evt.getSource())).transferFocus();

            } else {
                JOptionPane.showMessageDialog(this, "SENHA NAO CONFERE! \n"
                        + "VERIFIQUE OS CAMPOS SELECIONADOS ! ");

                jPasswordField_senha.setText("");
                jPasswordField_ConfirmaSenha.setText("");
                jPasswordField_senha.requestFocus();
            }
        }
    }//GEN-LAST:event_jPasswordField_ConfirmaSenhaKeyPressed

    private void txt_nomeUsuarioCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txt_nomeUsuarioCaretUpdate
        if ((txt_nomeUsuario.getText().equals(""))) {
            txt_login.setEnabled(false);

        } else {
            txt_login.setEnabled(true);
        }
    }//GEN-LAST:event_txt_nomeUsuarioCaretUpdate

    private void txt_loginKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_loginKeyPressed
        String login = txt_login.getText();
        int key = evt.getKeyCode();
        if (key == KeyEvent.VK_ENTER) {
            verificaLogin(login);
        }
    }//GEN-LAST:event_txt_loginKeyPressed

    private void jcbx_incluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbx_incluirActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jcbx_incluirActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        FormAlteraUsuario updateUser = new FormAlteraUsuario(conn);
        updateUser.setVisible(true);
        this.dispose();

    }//GEN-LAST:event_jButton2ActionPerformed

      private void resetUsuarios() {

          txt_login.setText("");
          txt_nomeUsuario.setText("");
          jPasswordField_senha.setText("");
          jPasswordField_ConfirmaSenha.setText("");
          carregaChebox();

      }

      public void carregaImagemUser() throws IOException, SQLException {
          login = txt_login.getText().toString();
          String caminhoArquivo = null;

          JFileChooser arquivo = new JFileChooser();

          JFileChooser fc = new JFileChooser();
// int = returnVal fc.showDialog (FileChooserDemo2.this, "Attach");
          arquivo.setCurrentDirectory(new File("./src/imagens"));

          FileNameExtensionFilter filter = new FileNameExtensionFilter("Arquivos de Imagens (.jpg/.png)", "jpg", "png");

          //ADICIONA A EXTENSAO NA TELA
          arquivo.addChoosableFileFilter(filter);

          //NAO LISTA TODOS OS ARQUIVOS
          arquivo.setAcceptAllFileFilterUsed(false);

          //Adiciona a janela de preview(visualizaÃ§Ã£o de imagem).
          arquivo.setAccessory(new ImagePreview(arquivo));
          //  this.JFileChooser.setCurrentDirectory(new File("C:/Sistemas/GerenteProjeto/src/gerenteprojeto/icons"));

          int result = arquivo.showOpenDialog(this);

          if (result == JFileChooser.APPROVE_OPTION) {

              caminhoArquivo = arquivo.getSelectedFile().getPath();

              // imgUser.setIcon(new ImageIcon(arq.getAbsolutePath()));

              File imagem = arquivo.getSelectedFile();//arquivo
              FileInputStream fs = new FileInputStream(caminhoArquivo);
              BufferedImage bi = ImageIO.read(imagem);//carrega a imagem real num buffer
              BufferedImage aux = new BufferedImage(100, 100, bi.getType());//cria um buffer auxiliar com o tamanho desejado
              Graphics2D g = aux.createGraphics();//pega a classe graphics do aux para edicao
              AffineTransform at = AffineTransform.getScaleInstance((double) 100 / bi.getWidth(), (double) 100 / bi.getHeight());//cria a transformacao
              g.drawRenderedImage(bi, at);//pinta e transforma a imagem real no auxiliar
              imgUser.setIcon(new ImageIcon(aux));//seta no jlabel
              // path = arq;
               byte[] b = new byte[(int) imagem.length()];
              foto = b;
              fis = fs;
            
             // insereImagem(login, imagem, fs);
          } else {
          }

      }
    public boolean inserirBlob(byte[] blob) throws SQLException {
       
        if (blob != null) {
           
              try {
            Statement stmt = (Statement) Conexao.conn.createStatement();

            String sql = "INSERT INTO dataserverreligadora.imagem (login,foto) VALUES ('alex','"+blob+"')";
                  System.out.println(sql);
            stmt.execute(sql);

           
        }catch(SQLException sqle){
                  System.out.println(sqle);
        }
        }
        return false;
    }
      public void insereImagem(String login, RenderedImage image, FileInputStream fis) throws IOException {

          ByteArrayOutputStream bytesImg = new ByteArrayOutputStream();
          ImageIO.write(image, "jpg", bytesImg);
        
          bytesImg.flush();

          byte[] byteArray = bytesImg.toByteArray();
          bytesImg.close(); 
          try {
              //Statement stmt = (Statement) Conexao.conn.createStatement();

              PreparedStatement pstmt =  (PreparedStatement) Conexao.conn.prepareStatement("INSERT INTO dataserverreligadora.imagem (login,foto) VALUES (?,?)");  

              pstmt.setString(1, login);  
              pstmt.setBytes(2, byteArray);  
pstmt.executeUpdate();  
pstmt.close();  
            //  String sql = "INSERT INTO imagem (login,foto) VALUES('" + login + "','" + image + "')";

             // stmt.execute(sql);

          } catch (Exception e) {
              System.out.println(e);
          }
      }

          public File capturaImagem(int cod) throws IOException{
		
		File image = null;
	 ImageIcon icone;
	 int iComp;
		FileOutputStream bout = null;
		byte[] bbuf = new byte[1024];
		int bytesRead = 0;
                BufferedImage img = null ;
		
		 //String sql = "SELECT foto FROM dataserverreligadora.imagem WHERE id = "+ cod;
		           // System.out.println(sql);
              try {
                  Statement stmt = (Statement) Conexao.conn.createStatement();

                  ResultSet rs = (ResultSet) stmt.executeQuery("SELECT foto FROM dataserverreligadora.imagem WHERE id = " + cod);
                  rs.next();

                  // copia arquivo para campo blob  
                  Blob blob = (Blob) rs.getBlob("foto");
                  //   fig = rs.getBlob("figura");  
                  iComp = (int) (blob.length());
                  icone = new ImageIcon(blob.getBytes(1L, iComp));
                  System.out.println(icone.getIconHeight());
                  System.out.println(icone.getIconWidth());
                  imgUser.setIcon(icone);
  // jLabel35 = new JLabel(new ImageIcon(imagecon));
    // imgUser.setIcon(imagecon);
                  InputStream bin = new FileInputStream("c:\\a.png");
                  // OutputStream bout = ((BLOB) blob).getBinaryOutputStream(); // específico driver oracle  
                  // cout = clob.setCharacterStream(0);  

                  while ((bytesRead = bin.read(bbuf)) != -1) {
                      bout.write(bbuf, 0, bytesRead);
                  }
                  bin.close();
                  bout.close();

              } catch (Exception e) {
                  //  out.print(e);  
              }



		
		//image = new File("teste.jpg");
		
//                File img = new File("C:\\..\\image.jpg");
//BufferedImage bufferedImage = ImageIO.read(img);
//ImageIcon imageIcon = new ImageIcon(bufferedImage);
//                
//                try{
//                      // BufferedImage fundo = ImageIO.read(bin);
//              ImageIcon icon = new ImageIcon(img.getScaledInstance(img.getWidth(), img.getHeight(), 10000));
//              imgUser.setIcon(icon);
//                }catch(NullPointerException ne){
//                    System.out.println(ne);
//                }
           
              return image;

      

		
	}
      /**
       * @param args the command line arguments
       */
      public static void main(String args[]) {
          java.awt.EventQueue.invokeLater(new Runnable() {

              public void run() {
 
                  new FormCadastroUsuario(null).setVisible(true);

              }
          });
      }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_cadastrar;
    private javax.swing.JButton btn_cancelar;
    private javax.swing.JComboBox cbx_tipoUser;
    private javax.swing.JLabel imgUser;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPasswordField jPasswordField_ConfirmaSenha;
    private javax.swing.JPasswordField jPasswordField_senha;
    private javax.swing.JCheckBox jcbx_alterar;
    private javax.swing.JCheckBox jcbx_consultar;
    private javax.swing.JCheckBox jcbx_excluir;
    private javax.swing.JCheckBox jcbx_incluir;
    private javax.swing.JCheckBox jcbx_todos;
    public static javax.swing.JTextField txt_login;
    public static javax.swing.JTextField txt_nomeUsuario;
    // End of variables declaration//GEN-END:variables

    public void verificaLogin(String login) {

        if ((login.equals(""))) {

            JOptionPane.showMessageDialog(this, "PREENCHA OS CAMPOS CORRETAMENTE \nVERIFIQUE OS CAMPOS DIGITADOS", "ATENÇÃO", JOptionPane.WARNING_MESSAGE);

            txt_login.requestFocus();

        } else if (login == null ? operacao.verificaLogin(login) == null : login.equals(operacao.verificaLogin(login))) {

            JOptionPane.showMessageDialog(this, "ATENÇÃO, VERIFIQUE O LOGIN DIGITADO", "ATENÇÃO", JOptionPane.WARNING_MESSAGE);
            JOptionPane.showMessageDialog(this, "EXISTE UM USUARIO COM MESMO LOGIN CADASTRADO NO SISTEMA! \n"
                    + "INSIRA UM NOVO USUARIO");

            txt_login.setText("");
            txt_login.requestFocus();

        } else {
            jPasswordField_senha.requestFocus();
        }
    }

    public void verificaCapsLock() {
        Toolkit tk = Toolkit.getDefaultToolkit();

        if (tk.getLockingKeyState(KeyEvent.VK_CAPS_LOCK)) {
            Icon ativo = new ImageIcon("C:\\cfgReligadora\\icons\\atencao_caps.png");
            jLabel5.setIcon(ativo);
            jLabel5.setToolTipText("Tecla CapsLock ativa");

        } else {

            Icon ativo = new ImageIcon();
            jLabel5.setIcon(ativo);
            jLabel5.setToolTipText(null);

        }
    }
 
    public class ControlarEntradaTexto extends PlainDocument {

        @Override
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            if (Character.isLetter(str.charAt(0)) || str.equals("")) //(!Character.isDigit(evt.getKeyChar()) && !Character.isLetter(evt.getKeyChar()))
            {
                super.insertString(offs, str.toUpperCase(), a);
            }
        }
    }

    //LIMITA QUANTIDADE DE CARACTERES NO TEXTFIEL SELECIONADO
    public class MaxLengthTextDocument extends PlainDocument {
        //Armazena o número máximo de caracteres para o texto.

        int valor = 10;

        @Override
        public void insertString(int offs, String str, AttributeSet a)
                throws BadLocationException {
            if (str != null && (getLength() + str.length() < valor)) {
                super.insertString(offs, str, a);
            }
        }
    }

    public class tirarAcento extends PlainDocument {

        @Override
        public void insertString(int offs, String str, AttributeSet a)
                throws BadLocationException {

            if (str == null) {
                return;
            }

            String naoacentuado = Normalizer.normalize(str.toLowerCase(), Normalizer.Form.NFD); // elimina os acentos.
            naoacentuado = naoacentuado.replaceAll("[^a-zA-Z0-9_]", ""); // remove as sujeiras do processo acima.

            super.insertString(offs, naoacentuado, a);
        }
    }

    public class formatNome extends PlainDocument {

        @Override
        public void insertString(int offs, String str, AttributeSet a)
                throws BadLocationException {

            if (str == null) {
                return;
            }

            String naoacentuado = Normalizer.normalize(str.toUpperCase(), Normalizer.Form.NFD); // elimina os acentos.
            naoacentuado = naoacentuado.replaceAll("[^a-z A-Z ]", ""); // remove as sujeiras do processo acima.

            super.insertString(offs, naoacentuado, a);
        }
    }

    public class semCentencas extends PlainDocument {

        int valor = 10;

        @Override
        public void insertString(int offs, String str, AttributeSet a)
                throws BadLocationException {

            if (str == null) {
                return;
            }

            String sentenca = Normalizer.normalize(str.toUpperCase(), Normalizer.Form.NFD); // elimina os acentos.
            sentenca = sentenca.replaceAll("[^a-z A-Z 0-9]", "");

            super.insertString(offs, sentenca, a);
        }
    }

    public class verificaEmail extends PlainDocument {

        @Override
        public void insertString(int offs, String str, AttributeSet a)
                throws BadLocationException {

            if (str == null) {
                return;
            }

            String sentenca = Normalizer.normalize(str.toUpperCase(), Normalizer.Form.NFD); // elimina os acentos.
            sentenca = sentenca.replaceAll("[^a-zA-Z-@.0-9_]", "");

            super.insertString(offs, sentenca, a);
        }
    }

    public class verificaSenha extends PlainDocument {

        @Override
        public void insertString(int offs, String str, AttributeSet a)
                throws BadLocationException {

            if (str == null) {
                return;
            }

            String sentenca = Normalizer.normalize(str, Normalizer.Form.NFD); // elimina os acentos.
            sentenca = sentenca.replaceAll("[^a-zA-Z0-9]", "");

            super.insertString(offs, sentenca, a);
        }
    }

    public class ImagePreview extends JComponent
            implements PropertyChangeListener {

        ImageIcon thumbnail = null;
        File file = null;

        public ImagePreview(JFileChooser fc) {
            setPreferredSize(new Dimension(180, 50));
            fc.addPropertyChangeListener(this);
        }

        public void loadImage() {
            if (file == null) {
                thumbnail = null;
                return;
            }

            ImageIcon tmpIcon = new ImageIcon(file.getPath());
            if (tmpIcon != null) {
                if (tmpIcon.getIconWidth() > 180) {
                    thumbnail = new ImageIcon(tmpIcon.getImage().
                            getScaledInstance(180, -1,
                            Image.SCALE_DEFAULT));
                } else { //no need to miniaturize
                    thumbnail = tmpIcon;
                }
            }
        }

        public void propertyChange(PropertyChangeEvent e) {
            boolean update = false;
            String prop = e.getPropertyName();

            //If the directory changed, don't show an image.
            if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) {
                file = null;
                update = true;

                //If a file became selected, find out which one.
            } else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {
                file = (File) e.getNewValue();
                update = true;
            }

            //Update the preview accordingly.
            if (update) {
                thumbnail = null;
                if (isShowing()) {
                    loadImage();
                    repaint();
                }
            }
        }

        protected void paintComponent(Graphics g) {
            if (thumbnail == null) {
                loadImage();
            }
            if (thumbnail != null) {
                int x = getWidth() / 2 - thumbnail.getIconWidth() / 2;
                int y = getHeight() / 2 - thumbnail.getIconHeight() / 2;

                if (y < 0) {
                    y = 0;
                }

                if (x < 5) {
                    x = 5;
                }
                thumbnail.paintIcon(this, g, x, y);
            }
        }
    }
}
